package com.vlad.domen.consumers;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import com.vlad.domen.Restaurant;
import com.vlad.domen.util.Logger;
import com.vlad.domen.util.Order;

public class Consumer implements Runnable {
	private final Restaurant restaurant;
	private final int id;
	private Order order;
	private Random random = new Random();

	public Consumer(Restaurant restaurant, int id) {
		super();
		this.restaurant = restaurant;
		this.id = id;
	}

	@Override
	public void run() {
		while (!Thread.interrupted()) {
			makeOrder();
			synchronized (this) {
				try {
					wait();
				} catch (InterruptedException e) {
					return;
				}
			}
			Logger.logWrite("" + new Date() + " " + this
					+ " received ready order " + order.getId() + "\n");
			try {
				TimeUnit.MILLISECONDS.sleep(random.nextInt(3000));
			} catch (InterruptedException e) {
				return;
			}
		}

	}

	private synchronized void makeOrder() {
		order = new Order(this);
		Logger.logWrite("" + new Date() + " " + this + " created new order "
				+ order.getId() + "\n");
		restaurant.takeOrder(order);
	}

	@Override
	public synchronized String toString() {
		return "Consumer " + id;
	}

}
